$(function () {
  var form = layui.form
  $('#image').cropper({
    aspectRatio: 1,
    preview: '.img-preview'
  })

  //文章类别渲染
  function getfenlei() {
    $.ajax({
      url: '/my/article/cates',
      type: 'get',
      data: {},
      success: function (res) {
        // console.log(res, 88888)
        var html = template('opt', res)
        $('#leibie').html(html)
        form.render()
      }
    })
  }
  getfenlei()

  //点击上传
  $('.upload').on('click', function () {
    $('#uploadFile').click()
  })
  //监听文件状态 获取文件上传的内容
  $('#uploadFile').on('change', function () {
    var files = $(this)[0].files
    // console.log(files,111111111);
    if (files.length <= 0) {
      alert('您未上传文件，请重新上传')
    }
    // console.log(files[0],11111);
    var url = URL.createObjectURL(files[0])
    console.log(url)
    $('#image').cropper('destroy').attr('src', url).cropper({
      aspectRatio: 1,
      preview: '.img-preview'
    })
  })

  //存为草稿
  var state = '已发布'
  $('.caogao').on('click', function () {
    state = '草稿'
  })
  //发布文章
  $('#pubform').on('submit', function (e) {
    e.preventDefault()
    var formdata = new FormData($('#pubform')[0])
    // console.log(formdata,1111)
    formdata.append('state', state)
    $('#image')
      .cropper('getCroppedCanvas', {
        width: 100,
        height: 100
      })
      .toBlob(function (blob) {
        formdata.append('cover_img', blob)
        $.ajax({
          url: '/my/article/add',
          type: 'post',
          data: formdata,
          processData: false, //  不改变默认content-type
          contentType: false, //  不改变 urlencoded  url编码格式
          success: function (res) {
            console.log(formdata.get('cover_img'), 111)
            location.href = '/artice/art_list.html'
          }
        })
      })
  })
})
